package com.ypx.ec.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.ypx.ec.common.exception.NoStockException;
import com.ypx.ec.common.to.mq.OrderTo;
import com.ypx.ec.common.to.mq.StockDetailTo;
import com.ypx.ec.common.to.mq.StockLockedTo;
import com.ypx.ec.common.utils.R;
import com.ypx.ec.ware.entity.WareOrderTaskDetailEntity;
import com.ypx.ec.ware.entity.WareOrderTaskEntity;
import com.ypx.ec.ware.feign.OrderFeignService;
import com.ypx.ec.ware.service.WareOrderTaskDetailService;
import com.ypx.ec.ware.service.WareOrderTaskService;
import com.ypx.ec.ware.vo.OrderItemVo;
import com.ypx.ec.ware.vo.OrderVo;
import com.ypx.ec.ware.vo.SkuHasStockVo;
import com.ypx.ec.ware.vo.WareSkuLockVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ypx.ec.common.utils.PageUtils;
import com.ypx.ec.common.utils.Query;

import com.ypx.ec.ware.dao.WareSkuDao;
import com.ypx.ec.ware.entity.WareSkuEntity;
import com.ypx.ec.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    WareOrderTaskService orderService;

    @Autowired
    WareOrderTaskDetailService orderDetailService;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    OrderFeignService orderFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }
    @Transactional
    @Override
    public void addSku(Long skuId, Long wareId, Integer stock) {
        List<WareSkuEntity> wareSkuEntities=
                baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id",skuId)
                        .eq("ware_id",wareId));
        if(wareSkuEntities==null|| wareSkuEntities.size()==0){
            WareSkuEntity wareSkuEntity=new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(stock);
            this.save(wareSkuEntity);
        }else {
            baseMapper.addSku(skuId,wareId,stock);
        }

    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            Integer count = baseMapper.selectCount(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId));
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(count != 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return collect;
    }
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        List<OrderItemVo> items = vo.getLocks();
        WareOrderTaskEntity taskEntity=new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        orderService.save(taskEntity);
        for (OrderItemVo item : items) {
            List<WareSkuEntity> wareSkuEntities = this.list(new QueryWrapper<WareSkuEntity>().eq("sku_id", item.getSkuId()));
            if(wareSkuEntities.size()==0 || wareSkuEntities==null){
                throw new NoStockException(item.getSkuId());
            }
            /**
             * 遍历库存
             */
            boolean hasStock=false;
            for (WareSkuEntity wareSkuEntity : wareSkuEntities) {
                Long count=this.baseMapper.lockSkuStock(wareSkuEntity.getSkuId(), wareSkuEntity.getWareId(), item.getCount());
                if(count!=0){
                    hasStock=true;
                    WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity(null, wareSkuEntity.getWareId(), "", item.getCount(), taskEntity.getId(), wareSkuEntity.getWareId(), 1);
                    orderDetailService.save(detailEntity);
                    StockLockedTo to = new StockLockedTo();
                    StockDetailTo detailTo = new StockDetailTo();
                    to.setId(taskEntity.getId());
                    BeanUtils.copyProperties(detailEntity, detailTo);
                    //防止回滚之后找不到数据,所以保存完整库存单
                    to.setDetail(detailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", to);
                    break;
                }
            }
            if (!hasStock){
                throw new NoStockException(item.getSkuId());
            }
        }
        return true;

    }

    @Override
    public void unlockStock(StockLockedTo to) {
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        //解锁库存
        //1.查询关于这个订单的锁定库存信息
        WareOrderTaskDetailEntity orderTaskDetailEntity = orderDetailService.getById(detailId);
        if (orderTaskDetailEntity != null) {
            //有,库存锁定成功，根据订单情况解锁
            Long id = to.getId();//库存工作单Id
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                OrderVo data = r.getData(new TypeReference<OrderVo>() {
                });
                if (data == null || data.getStatus() == 4) {
                    //没有这个订单 或者 有订单但订单状态是已取消,解锁库存
                    //只有状态是1,才能解锁
                    if (orderTaskDetailEntity.getLockStatus() == 1) {
                        unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                    }
                }
            } else {
                //其它状态(包含订单成功)不解锁
                throw new RuntimeException("远程服务失败");
            }
        } else {
            //没有，库存锁定失败，库存回滚，这种情况无需解锁
        }
    }

    @Override
    public void unlockStock(OrderTo orderDTO) {
        String orderSn = orderDTO.getOrderSn();
        WareOrderTaskEntity taskEntity = wareOrderTaskService.getOne(new QueryWrapper<WareOrderTaskEntity>().eq("order_sn", orderSn));
        List<WareOrderTaskDetailEntity> detailEntities=orderDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id",taskEntity.getId()));
        for (WareOrderTaskDetailEntity ele : detailEntities) {
            unLockStock(ele.getSkuId(),ele.getWareId(),ele.getSkuNum(),ele.getId());
        }
    }


    public void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        //库存解锁
        this.baseMapper.unlockStock(skuId, wareId, num);
        //更新库存工作单状态
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(taskDetailId);
        entity.setLockStatus(2);
        orderDetailService.updateById(entity);
    }


}